<template>
	<div class="container">
		<!-- 搜索栏 -->
		<div class="search-bar">
			<div class="search-input">
				<img src="/src/assets/images/search.png" class="search-icon" />
				<span class="placeholder">搜索商品</span>
			</div>
		</div>

		<!-- 轮播图 -->
		<van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
			<van-swipe-item v-for="(item,index) in banners" :key="item.image">
				<img :src="item.image" alt="" />
			</van-swipe-item>
		</van-swipe>

		<!-- 分类图标 -->
		<div class="category-icons">
			<div class="icon-item" v-for="(item, index) in categories" :key="index"  @click="handleClick(index)">
				<img :src="item.icon" class="icon-image" />
				<span class="icon-text">{{ item.name }}</span>
			</div>
		</div>

		<!-- 秒杀专区 -->
		<div class="seckill-section">
			<div class="section-header">
				<div class="header-left">
					<span class="title">限时秒杀</span>
					<span class="time">剩余时间: {{ hours }}:{{ minutes }}:{{ seconds }}</span>
				</div>
				<span class="more">更多 ></span>
			</div>
			<div class="seckill-list-wrapper">
				<div class="seckill-list">
					<div class="seckill-item" v-for="(item, index) in seckillGoods" :key="index" @click="gotoDetail(item.id)">
						<div class="item-content">
							<img class="item-image" :src="item.cover" mode="aspectFit" />
							<div class="price-info">
								<span class="price">¥{{ item.price.toFixed(2) }}</span>
								<span
									class="original-price">¥{{ (item.originalPrice || item.price * 1.5).toFixed(2) }}</span>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 推荐商品 - 瀑布流布局 -->
		<div class="recommend-section">
			<div class="section-header">
				<span class="title">猜你喜欢</span>
			</div>
			<div class="waterfall-container">
				<div class="waterfall-column" ref="leftColumn">
					<div class="goods-item" v-for="(item, index) in leftColumnGoods" :key="index" @click="gotoDetail(item.id)">
						<img :src="item.cover" class="goods-image" />
						<div class="goods-info">
							<div class="name">{{ item.name }}</div>
							<div class="price-line">
								<span class="price">¥{{ item.price.toFixed(2) }}</span>
								<span class="sold">已售 {{ item.sold }}</span>
							</div>
						</div>
					</div>
				</div>
				<div class="waterfall-column" ref="rightColumn">
					<div class="goods-item" v-for="(item, index) in rightColumnGoods" :key="index" @click="gotoDetail(item.id)">
						<img :src="item.cover" class="goods-image" />
						<div class="goods-info">
							<div class="name">{{ item.name }}</div>
							<div class="price-line">
								<span class="price">¥{{ item.price.toFixed(2) }}</span>
								<span class="sold">已售 {{ item.sold }}</span>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<!-- 底部显示 -->
		<div class="bottom-line">
			<div class="line"></div>
			<span class="line-text">我也是有底线的</span>
			<div class="line"></div>
		</div>
	</div>
</template>

<script>
	import {
		ref,
		onMounted,
		onUnmounted,
		nextTick
	} from 'vue'; 
	import {
		getCreateProductsList
	} from '@/apis/products'
	import { useRouter, useRoute } from 'vue-router'
	
	
	export default {

		setup() {
			const router = useRouter()
			const route = useRoute()
			// 轮播图数据
			const banners = ref([{
					image: '/images/good1.jpg'
				},
				{
					image: '/images/good2.jpg'
				},
				{
					image: '/images/good3.jpg'
				}
			]);

			// 分类图标数据
			const categories = ref([{
					icon: '/images/daily.png',
					name: '每日推荐'
				},
				{
					icon: '/images/box.png',
					name: '盲盒'
				},
				{
					icon: '/images/china.png',
					name: '瓷器'
				},
				{
					icon: '/images/cosmetics.png',
					name: '美妆'
				},
				{
					icon: '/images/bag.png',
					name: '箱包'
				},
				{
					icon: '/images/stationery.png',
					name: '文具'
				},
				{
					icon: '/images/jewelry.png',
					name: '饰品'
				},
				{
					icon: '/images/more.png',
					name: '更多'
				}
			]);
			// 初始化数据
			const seckillGoods = ref([]); //限时秒杀
			const recommendGoods = ref([]);//猜你喜欢
			
			// 瀑布流左右列商品
			const leftColumnGoods = ref([]);
			const rightColumnGoods = ref([]);
			
			// 倒计时相关
			const hours = ref('00');
			const minutes = ref('00');
			const seconds = ref('00');
			let countdownTimer = null;

			// DOM引用
			const leftColumn = ref(null);
			const rightColumn = ref(null);

			// 初始化瀑布流布局
			const initWaterfall = () => {
				// 清空列
				leftColumnGoods.value = [];
				rightColumnGoods.value = [];

				// 交替分配商品到左右列
				recommendGoods.value.forEach((item, index) => {
					if (index % 2 === 0) {
						leftColumnGoods.value.push(item);
					} else {
						rightColumnGoods.value.push(item);
					}
				});
			};

			// 更新倒计时
			const updateCountdown = () => {
				const endTime = new Date();
				endTime.setHours(endTime.getHours() + 2); // 设置2小时后的时间

				const update = () => {
					const now = new Date();
					const diff = endTime - now;

					if (diff <= 0) {
						hours.value = '00';
						minutes.value = '00';
						seconds.value = '00';
						clearInterval(countdownTimer);
						return;
					}

					const h = Math.floor(diff / (1000 * 60 * 60));
					const m = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
					const s = Math.floor((diff % (1000 * 60)) / 1000);

					hours.value = h.toString().padStart(2, '0');
					minutes.value = m.toString().padStart(2, '0');
					seconds.value = s.toString().padStart(2, '0');
				};

				// 立即更新一次
				update();
				// 每秒更新一次
				countdownTimer = setInterval(update, 1000);
			};
			// 跳转
			const handleClick = (index) => {
			    if (index === 7) {
			         router.push({
			            name: 'more',
			          })
			    }
			};
			const getCreateProducts = () => {
				getCreateProductsList().then(res => {
					if (res && res.data) {
						// 设置处理秒杀商品数据
						const shuffled = [...res.data].sort(() => 0.5 - Math.random());
						const seckillSelected = shuffled.slice(0, 6);

						// 设置秒杀商品数据
						seckillGoods.value = seckillSelected.map(item => ({
							id: item.id,
							cover: item.cover,
							price: item.price,
							originalPrice: item.originalPrice || item.price * 1.5,
							name: item.productName
						}));

						// 设置猜你喜欢数据
						recommendGoods.value = res.data.map(item => ({
							id: item.id,
							cover: item.cover,
							name: item.productName || '未命名商品',
							price: item.price,
							sold: item.sold || Math.floor(Math.random() * 1000) // 如果没有销量则随机生成
						}));

						// 3. 初始化瀑布流布局
						nextTick(() => {
							initWaterfall();
						});
					}
				}).catch(error => {
					console.error('获取商品失败:', error);
				});
			};
			const gotoDetail = (id) => {
				router.push({
				   name: 'detail',
				   query: { id },
				 })
				
			}
			const init = () => {
				getCreateProducts()
			}
			onMounted(() => {
				updateCountdown();
				init(); //初始化
				// 监听窗口大小变化，重新布局瀑布流
				window.addEventListener('resize', initWaterfall);
			});

			onUnmounted(() => {
				// 清理定时器和事件监听器
				if (countdownTimer) {
					clearInterval(countdownTimer);
				}
				window.removeEventListener('resize', initWaterfall);
			});
			return {
				banners,
				categories,
				seckillGoods,
				recommendGoods,
				leftColumnGoods,
				rightColumnGoods,
				hours,
				minutes,
				seconds,
				leftColumn,
				rightColumn,
				getCreateProducts,
				handleClick,
				gotoDetail
			};
		}
	};
</script>

<style scoped>
	/* 基础样式 */
	.container {
		padding-bottom: 25px;
		background-color: #f7f7f7;
		font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
	}

	/* 搜索栏样式 */
	.search-bar {
		padding: 10px 15px;
		background-color: #8b0000;
	}

	.search-input {
		background-color: #fff;
		border-radius: 25px;
		height: 35px;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #999;
	}

	.search-icon {
		width: 16px;
		height: 16px;
	}

	.placeholder {
		font-size: 14px;
		margin-left: 5px;
	}

	/* 轮播图样式 */
	.my-swipe {
		width: 100%;
		height: 200px;
		overflow: hidden;
	}

	.my-swipe img {
		width: 100%;
		height: 100%;
		object-fit: fill;
		/* 使图片保持纵横比并覆盖整个容器 */
	}

	/* 分类图标样式 */
	.category-icons {
		display: flex;
		flex-wrap: wrap;
		padding: 10px 0;
		background-color: #fff;
		margin-bottom: 10px;
	}

	.icon-item {
		width: 25%;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin: 10px 0;
	}

	.icon-image {
		width: 40px;
		height: 40px;
		object-fit: contain;
	}

	.icon-text {
		font-size: 12px;
		margin-top: 5px;
		color: #333;
	}

	/* 秒杀专区样式 */
	.seckill-section {
		margin-top: 10px;
		background-color: #fff;
		padding: 15px;
		border-radius: 8px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
	}

	.section-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 15px;
	}

	.header-left {
		display: flex;
		align-items: center;
	}

	.title {
		font-size: 17px;
		font-weight: bold;
		color: #e01111;
		margin-right: 10px;
	}

	.time {
		font-size: 13px;
		color: #8b0000;
		background-color: #ffeee6;
		padding: 2px 6px;
		border-radius: 10px;
		display: flex;
		align-items: center;
	}

	.more {
		font-size: 13px;
		color: #999;
	}

	.seckill-list-wrapper {
		overflow-x: auto;
		-webkit-overflow-scrolling: touch;
	}

	.seckill-list {
		display: flex;
		padding-bottom: 5px;
		width: max-content;
	}

	.seckill-item {
		width: 110px;
		margin-right: 12px;
	}

	.item-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: #fff;
		border-radius: 6px;
		overflow: hidden;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
	}

	.item-image {
		width: 100%;
		height: 100px;
		object-fit: cover;
	}

	.price-info {
		display: flex;
		align-items: baseline;
		justify-content: center;
		width: 100%;
		padding: 5px;
	}

	.price {
		color: #e01111;
		font-size: 16px;
		font-weight: bold;
	}

	.original-price {
		color: #999;
		font-size: 12px;
		text-decoration: line-through;
		margin-left: 3px;
	}

	/* 推荐商品 - 瀑布流布局样式 */
	.recommend-section {
		padding: 15px;
	}

	.waterfall-container {
		display: flex;
		justify-content: space-between;
	}

	.waterfall-column {
		width: 49%;
	}

	.goods-item {
		background-color: #fff;
		border-radius: 5px;
		overflow: hidden;
		margin-bottom: 10px;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
	}

	.goods-image {
		width: 100%;
		height: auto;
		object-fit: cover;
	}

	.goods-info {
		padding: 8px;
	}

	.name {
		font-size: 13px;
		color: #333;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
		margin-bottom: 5px;
		line-height: 1.4;
		height: 36px;
	}

	.price-line {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.sold {
		font-size: 11px;
		color: #999;
	}

	/* 底部显示样式 */
	.bottom-line {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		padding: 20px 0;
		color: #999;
	}

	.line {
		width: 50px;
		height: 1px;
		background-color: #e5e5e5;
		margin: 0 10px;
	}

	.line-text {
		font-size: 12px;
		color: #999;
	}
</style>